// --------------------------------------------------------------------------------------------------------------------
// <copyright file="KinectPoseUpdaterAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Runtime.Perception
{
    using System;
    using System.Runtime.Serialization;

    using Microsoft.Robotics.Hardware.DAC;
    using Microsoft.Robotics.Hardware.Runtime.DAC;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Vision.Cameras;
    using Microsoft.Robotics.Vision.Runtime.Cameras;

    /// <summary>
    /// This agent synchronizes Kinect and Joint (turret in case of Max) and re-publishes Kinect message with updated pose
    /// Notes: there can be all kinds of cameras and other devices like IR/Sonars, which we might want to control the 
    /// pose of, so it would make sense to have a generic "Device Pose Updater" agent, as opposed to having a pose as 
    /// part of the sensor message. The idea makes sense, but as Ashley pointed out - this is a type system limitations. 
    /// Either we have proliferation of message types (with and w/o poses) or update pose when applicable.
    /// </summary>
    /// <remarks>
    /// Updates KinectAgentMessages to contain robot-relative pose taking turret
    /// pan and tilt joint feedback into account.
    /// </remarks>
    [DataContract]
    public class KinectPoseUpdaterAgent : SynchronizedConsumerProducerAgent<DepthCameraAgentMessage<KinectDepthCameraParameters>, JointMessage, DepthCameraAgentMessage<KinectDepthCameraParameters>>
    {
        /// <summary>
        /// The maximum time delay allowed while still considering two messages as being in sync
        /// The value should be half the period of the fastest producer.
        /// </summary>
        private const int DefaultSyncTolerance = 1;

        /// <summary>
        /// The name of the Kinect agent we subscribe to.
        /// </summary>
        [DataMember(Name = "KinectMessageProducer")]
        private readonly string kinectMessageProducer;

        /// <summary>
        /// The name of the pan/tilt joint position producer we subscribe to.
        /// </summary>
        [DataMember(Name = "JointMessageProducer")]
        private readonly string jointMessageProducer;

        /// <summary>
        /// Index within JointMessage.State representing the hood tilt.
        /// </summary>
        [DataMember(Name = "TiltJointIndex")]
        private readonly int? tiltJointIndex;

        /// <summary>
        /// Index within JointMessage.State representing the turret pan.
        /// </summary>
        [DataMember(Name = "PanJointIndex")]
        private readonly int? panJointIndex;

        /// <summary>
        /// Initializes a new instance of the <see cref="KinectPoseUpdaterAgent" /> class.
        /// </summary>
        /// <param name="name">This agent name</param>
        /// <param name="kinectMessageProducer">Kinect agent message producer name</param>
        /// <param name="jointMessageProducer">Pan/Tilt joint info producer agent name</param>
        /// <param name="tiltJointIndex">Index within JointMessage.State representing the hood tilt.</param>
        /// <param name="panJointIndex">Index within JointMessage.State representing the turret pan.</param>
        public KinectPoseUpdaterAgent(
            string name,
            string kinectMessageProducer,
            string jointMessageProducer,
            int tiltJointIndex,
            int panJointIndex)
            : base(name, DefaultSyncTolerance)
        {
            this.kinectMessageProducer = kinectMessageProducer;
            this.jointMessageProducer = jointMessageProducer;
            this.tiltJointIndex = tiltJointIndex;
            this.panJointIndex = panJointIndex;
        }

        /// <summary>
        /// Needs to be provided for the synchronization
        /// </summary>
        protected override string ProducerName1
        {
            get { return this.kinectMessageProducer; }
        }

        /// <summary>
        /// Needs to be provided for the synchronization
        /// </summary>
        protected override string ProducerName2
        {
            get { return this.jointMessageProducer; }
        }

        /// <summary>
        /// Initialize the agent
        /// </summary>
        /// <param name="locator">The agent locator</param>
        public override void Initialize(AgentLocator locator)
        {
            if (this.kinectMessageProducer == default(string) ||
                this.jointMessageProducer == default(string) ||
                !this.tiltJointIndex.HasValue ||
                !this.panJointIndex.HasValue)
            {
                throw new ArgumentException(string.Format("At least one required initialization parameter is missing for {0}.", this.GetType().FullName));
            }

            base.Initialize(locator);
        }

        /// <summary>
        /// Synchronized Kinect and turret joint message.
        /// Applies turret pan and hood tilt to mounted Kinect pose.
        /// </summary>
        /// <param name="kinectMsg">Kinect message</param>
        /// <param name="jointMsg">Turret joint message</param>
        protected override void Receive(DepthCameraAgentMessage<KinectDepthCameraParameters> kinectMsg, JointMessage jointMsg)
        {
            double turretTilt = jointMsg.State[this.tiltJointIndex.Value].PositionInRadians;
            double turretPan = jointMsg.State[this.panJointIndex.Value].PositionInRadians;
            DepthCameraAgentMessage<KinectDepthCameraParameters> newMsg = new DepthCameraAgentMessage<KinectDepthCameraParameters>(kinectMsg);
            newMsg.Parameters.Pose = KinectPoseUpdater.UpdatePose(kinectMsg.Parameters.Pose, turretTilt, turretPan);
            this.Publisher.Post(newMsg);
        }
    }
}
